package com.kb.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.entity.ComponentData;
import com.kb.entity.ModelApplication;
import com.kb.entity.WaitPartNumber;
import com.kb.mapper.mysql.ComponentDao;
import com.kb.mapper.sqlServer.WaitPartNumberMapper;
import com.kb.service.ComponentDataService;
import com.kb.service.WaitPartNumberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

@DS("master")
@Service
@Slf4j
@RequiredArgsConstructor
public class WaitPartNumberServiceImpl extends ServiceImpl<WaitPartNumberMapper, WaitPartNumber> implements WaitPartNumberService {

    private final ComponentDataService componentDataService;
    private final ComponentDao componentDao;

    @Override
    public Boolean syncWaitPartNumber() throws InterruptedException {
        int successCount = 0;
        // 持续处理直到成功50次
        while (successCount < 2000) {
            // 每次获取一条未同步的数据
            WaitPartNumber waitPartNumber = baseMapper.selectOne(Wrappers.<WaitPartNumber>lambdaQuery()
                    .eq(WaitPartNumber::getSynchronization, 0)
                    .last("limit 1"));

            // 如果没有更多未同步数据，提前退出
            if (waitPartNumber == null) {
                break;
            }

            ModelApplication modelApplication = new ModelApplication();
            modelApplication.setPartNumber(waitPartNumber.getPartNumber());
            modelApplication.setType(2);

            if (Objects.nonNull(waitPartNumber.getOrgName())) {
                modelApplication.setOrgName(waitPartNumber.getOrgName());
            }
            //查询表是否没有这个型号
            LambdaQueryWrapper<ComponentData> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ComponentData::getPartNumber, waitPartNumber.getPartNumber());
            queryWrapper.last("limit 1");
//            ComponentData componentData = componentDao.selectOne(queryWrapper);
            int synchronization;
            Integer status;
//            if (Objects.nonNull(componentData)){
//                log.info("component_data表已存在型号: "+waitPartNumber.getPartNumber());
//                synchronization = 1;
//                status = 1;
//            }else {
                modelApplication.setCreateBy("KOM");
                Thread.sleep(50);
                log.info("同步成功: {}", JSONUtil.parse(modelApplication));
                 status = componentDataService.partNumber2Id(modelApplication);
                synchronization = Arrays.asList(1, 2).contains(status) ? 1 : 2;
//            }
            // 更新同步状态
            baseMapper.update(null, Wrappers.<WaitPartNumber>lambdaUpdate()
                    .set(WaitPartNumber::getSynchronization, synchronization)
                    .set(WaitPartNumber::getSyncTime, LocalDateTime.now())
                    .eq(WaitPartNumber::getId, waitPartNumber.getId()));

            // 如果同步成功，增加成功计数
            if (status == 1) {
                successCount++;
            }
        }
        return Boolean.TRUE;
    }

//    @Override
//    public Boolean syncWaitPartNumber() {
//        // 创建固定大小的线程池，可根据实际情况调整
//        ExecutorService executorService = Executors.newFixedThreadPool(10);
//
//        // 使用原子整型来统计成功的数量
//        AtomicInteger successCount = new AtomicInteger(0);
//
//        // 使用集合存储任务Future，方便管理
//        List<Future<?>> futures = new ArrayList<>();
//
//        // 提交多个任务到线程池
//        for (int i = 0; i < 1000; i++) {
//            Future<?> future = executorService.submit(() -> {
//                while (successCount.get() < 1000) {
//                    // 获取一条未同步的数据
//                    WaitPartNumber waitPartNumber = baseMapper.selectOne(
//                            Wrappers.<WaitPartNumber>lambdaQuery()
//                                    .eq(WaitPartNumber::getSynchronization, 0)
//                                    .last("limit 1")
//                    );
//
//                    // 如果没有更多未同步数据，则退出
//                    if (waitPartNumber == null) {
//                        break;
//                    }
//
//                    try {
//                        processSingleItem(waitPartNumber, successCount);
//                    } catch (Exception e) {
//                        log.error("处理 WaitPartNumber 失败, id={}", waitPartNumber.getId(), e);
//                    }
//                }
//            });
//            futures.add(future);
//        }
//
//        // 等待所有任务完成
//        for (Future<?> future : futures) {
//            try {
//                future.get();
//            } catch (InterruptedException | ExecutionException e) {
//                log.error("等待任务完成时发生错误", e);
//            }
//        }
//
//        // 关闭线程池
//        executorService.shutdown();
//
//        return Boolean.TRUE;
//    }
//
//    /**
//     * 单条记录处理逻辑抽取为单独方法
//     */
//    private void processSingleItem(WaitPartNumber waitPartNumber, AtomicInteger successCount) {
//        ModelApplication modelApplication = new ModelApplication();
//        modelApplication.setPartNumber(waitPartNumber.getPartNumber());
//        modelApplication.setType(2);
//
//        if (Objects.nonNull(waitPartNumber.getOrgName())) {
//            modelApplication.setOrgName(waitPartNumber.getOrgName());
//        }
//
//        // 查询表是否没有这个型号
//        LambdaQueryWrapper<ComponentData> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(ComponentData::getPartNumber, waitPartNumber.getPartNumber());
//        queryWrapper.last("limit 1");
//        ComponentData componentData = componentDao.selectOne(queryWrapper);
//
//        int synchronization;
//        Integer status;
//
//        if (Objects.nonNull(componentData)) {
//            log.info("component_data表已存在型号: " + waitPartNumber.getPartNumber());
//            synchronization = 1;
//            status = 1;
//        } else {
//            modelApplication.setCreateBy("KOM");
//            status = componentDataService.partNumber2Id(modelApplication);
//            synchronization = Arrays.asList(1, 2).contains(status) ? 1 : 2;
//        }
//
//        // 更新同步状态
//        baseMapper.update(null, Wrappers.<WaitPartNumber>lambdaUpdate()
//                .set(WaitPartNumber::getSynchronization, synchronization)
//                .set(WaitPartNumber::getSyncTime, LocalDateTime.now())
//                .eq(WaitPartNumber::getId, waitPartNumber.getId()));
//
//        // 如果同步成功，增加成功计数
//        if (status != null && status == 1) {
//            successCount.incrementAndGet();
//        }
//    }

}
